//
//  HOTProfileSettingViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-25.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTProfileSettingViewController.h"
#import "ZZZUIScrollView+Extends.h"
#import "HOTProfileReviewViewController.h"
#import "ZZZDatePicker.h"
#import "HOTBloodChooseViewController.h"
#import "HOTIntroductionSelfViewController.h"
#import "HOTCommChooseViewController.h"
#import "UITextField+extend.h"
#import "HOTProfileModel.h"
#import "HOTEvaluationListViewController.h"
#import "HOTFriendListViewController.h"

@interface HOTProfileSettingViewController () <HOTBloodChooseViewControllerDelegate, ZZZPopupViewDelegate>{
    
    ZZZDatePicker *_datePicker;
    
    __unsafe_unretained HOTProfileSettingViewController *blockObj;
    
    NSString *_selBloodId;
    NSString *_selBloodName;
    
    NSString *_selJobId;  //选择业种的id
    NSString *_selJobName;//选择业种的名称
    
    NSString *_selBaoyouzigeId;  //选择保有资格的id
    NSString *_selBaoyouzigeName;//选择保有资格的名称
    
    NSString *_selHealthId;  //选择健康診断的id
    NSString *_selHealthName;//选择健康診断的名称
    
    NSMutableArray *_jobInfoList;
    NSMutableArray *_healthList;
    NSMutableArray *_capcityInfoList;
    
    HOTProfileModel *_proFileModel;
}

@end

@implementation HOTProfileSettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    blockObj = self;
    
    [self setNaviTitle:@"プロフィール設定" fontSize:20 fontName:HOTTitleFont_ROUNDED_X];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_profile"]];
    
    [self addRightBtnTarget:self action:@selector(comfirmBtnClicked:) image:[UIImage imageNamed:@"btn_save_off"] hImage:[UIImage imageNamed:@"btn_save_on"]];
    
    [self initView];
    
    [self requestDataFromNet];
}

-(void)initView {
    
    __block UITextField *blockBirthdayText = _birthdayText;
    _datePicker = [ZZZDatePicker createWithTextField:_birthdayText
                                 doneCompletionBlock:^(NSDate *selDate) {
                                     
                                     NSString *dateStr = [ZZZUtils formartDate:selDate withStyle:@"yyyy-MM-dd"];
                                     blockBirthdayText.text = [HOTUtils getString:dateStr];
                                     
                                 }
                               cancelCompletionBlock:^{
                                   
                                   
                               }];
    [_datePicker setMaximumDate:[NSDate date]];
    [_datePicker setDatePickerMode:UIDatePickerModeDate];
    
    //性别
    ZZZPullDownModel *model = [[ZZZPullDownModel alloc] init];
    model.titleStr = @"男";
    model.value = @"1";
    
    ZZZPullDownModel *model2 = [[ZZZPullDownModel alloc] init];
    model2.titleStr = @"女";
    model2.value = @"2";
    [_sexPullDownView setSelectedModel:model];
    _sexPullDownView.parentView = _mainScrollView;
    _sexPullDownView.backgroundColor = [UIColor clearColor];
    _sexPullDownView.titleLab.textAlignment = NSTextAlignmentLeft;
    //[_sexPullDownView setTitleEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
    [_sexPullDownView setTitleFont:ZZZ_fontWithName(kHOT_FONT_HIRAGINO_KAKU_W6, 14)];
    [_sexPullDownView setPullDownModelList:@[model, model2]];
    [_sexPullDownView setWhenBtnClicked:^{
        [blockObj hiddenKeyBoard];
    }];
    
    //居住地
    
    _cityPullDownView.parentView = _mainScrollView;
    _cityPullDownView.backgroundColor = [UIColor clearColor];
    _cityPullDownView.WhenBtnClicked = ^(void) {
        
        [blockObj hiddenKeyBoard];
        [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    };
    
    _cityPullDownView.titleLab.textAlignment = NSTextAlignmentLeft;
    //[_cityPullDownView setTitleEdgeInsets:UIEdgeInsetsMake(0, -50, 0, 0)];
    [_cityPullDownView setTitleFont:ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 14)];
    
    NSArray *modelList = [HOTUtils getPullModelListFromPlist];
    [_cityPullDownView setSelectedModel:[modelList firstObject]];
    [_cityPullDownView setPullDownModelList:modelList];
    
    _rateView.paddingW = 3;
    _rateView.userInteractionEnabled = NO;
    [_rateView setImagesDeselected:@"icon_star_off" partlySelected:@"icon_star2" fullSelected:@"icon_star_on" andDelegate:nil];
    [_rateView displayRating:0];
}

/**
 *  获取用户数据
 */
-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_TARGET_UID:self.userInfo.userId
                                 };
    
    __unsafe_unretained HOTProfileSettingViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_GET_INFO Parameters:parameters success:^(NSInteger result, NSDictionary * userInfo) {

        if (userInfo) {
            //更新界面
            [tempObj updateView:userInfo];
        }
        [tempObj loadingSuccess];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)requestUpdate {

    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_USER_NICK:_nickNameText.text,
                                 REQ_KEY_USER_SEX:_sexPullDownView.selectedModel.value,
                                 REQ_KEY_USER_BIRTH:_birthdayText.text,
                                 REQ_KEY_CITY_ID:_cityPullDownView.selectedModel.value,
                                 REQ_KEY_USER_BLOOD:_selBloodId,
                                 REQ_KEY_USER_HEALTH:_selHealthId,
                                 REQ_KEY_USER_JOB_ID:_selJobId,
                                 REQ_KEY_USER_JOB_NAME:_selJobName,
                                 REQ_KEY_SELF_INTRO:_introductionLabel.text,
                                 REQ_KEY_USEr_CERTIFICATION_ID:_selBaoyouzigeId};
    
    __unsafe_unretained HOTProfileSettingViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_EDIT_INFO Parameters:parameters success:^(NSInteger result, NSDictionary * data) {

        
        [tempObj showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [tempObj performSelector:@selector(backBtnClicked:) withObject:nil afterDelay:0.8];
        }];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)updateView:(NSDictionary *)userInfo {
    
    //update userInfo
    self.userInfo.nick = [HOTUtils getString:[userInfo objectForKey:@"user_nick"]];
    self.userInfo.email = [HOTUtils getString:[userInfo objectForKey:@"user_email"]];
    self.userInfo.pwd = [HOTUtils getString:[userInfo objectForKey:@"user_pwd"]];
    self.userInfo.sex = [HOTUtils getString:[userInfo objectForKey:@"user_sex"]];
    self.userInfo.birth = [HOTUtils getString:[userInfo objectForKey:@"user_birth"]];
    self.userInfo.city_id = [HOTUtils getString:[userInfo objectForKey:@"city_id"]];
    self.userInfo.email = [HOTUtils getString:[userInfo objectForKey:@"user_email"]];
    self.userInfo.job_name = [HOTUtils getString:[userInfo objectForKey:@"job_name"]];
    
    self.userInfo.blood = [HOTUtils getString:[userInfo objectForKey:@"blood"]];
    self.userInfo.health = [HOTUtils getString:[userInfo objectForKey:@"health"]];
    self.userInfo.district = [HOTUtils getString:[userInfo objectForKey:@"district"]];
    self.userInfo.self_intro = [HOTUtils getString:[userInfo objectForKey:@"self_intro"]];
    self.userInfo.job_id = [HOTUtils getString:[userInfo objectForKey:@"job_id"]];
    self.userInfo.certification = [HOTUtils getString:[userInfo objectForKey:@"certification_id"]];
    self.userInfo.rate = [HOTUtils getString:[userInfo objectForKey:@"rate"]];
    self.userInfo.follow_sum = [HOTUtils getString:[userInfo objectForKey:@"follow_sum"]];

    [self.userInfo save];
    
    _nickNameText.text = self.userInfo.nick;
    [_sexPullDownView setSelectedModelByValue:self.userInfo.sex];
    
    _birthdayText.text = self.userInfo.birth;
    [_cityPullDownView setSelectedModelByValue:self.userInfo.city_id];
    
    _selBloodId = self.userInfo.blood;
    _bloodLabel.text = [self.userInfo bloodName];
    _selBloodName = _bloodLabel.text;
    
    _workTypeLabel.text = [self.userInfo jobName];
    _selJobId = self.userInfo.job_id;
    _selJobName = _workTypeLabel.text;
    
    _selBaoyouzigeId = self.userInfo.certification;
    _capacityLabel.text = self.userInfo.certificationName;
    _selBaoyouzigeName = _capacityLabel.text;
    
    _selHealthId = self.userInfo.health;
    _healthLabel.text = self.userInfo.healthName;
    _selHealthName = _healthLabel.text;
    
    _introductionLabel.text = self.userInfo.self_intro;
    
    _friendsLabel.text = [NSString stringWithFormat:@"%@人",self.userInfo.follow_sum];
    
    
    [_rateView displayRating:self.userInfo.rate.floatValue];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    [_mainScrollView scrollViewToVisible:textField.superview animated:YES];
    
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)chooseBloodId:(NSString *)bloodId bloodName:(NSString *)bName {
    
    _selBloodId = [HOTUtils getString:bloodId];
    _selBloodName = [HOTUtils getString:bName];
    
    _bloodLabel.text = _selBloodName;
}

#pragma mark - 按钮点击事件
- (IBAction)bloodBtnClicked:(id)sender {
    
    HOTBloodChooseViewController *bloodVc = [[HOTBloodChooseViewController alloc] initWithNibName:@"HOTBloodChooseViewController" bundle:nil selBloodId:_selBloodId];
    bloodVc.delegate = self;
    [self.navigationController pushViewController:bloodVc animated:YES];

}

- (IBAction)workTypeBtnClicked:(id)sender {
    
    HOTCommChooseViewController *ccvc = [[HOTCommChooseViewController alloc] initWithNibName:@"HOTCommChooseViewController" bundle:nil choosedInfo:@{@"id":[HOTUtils getString:_selJobId], @"name":[HOTUtils getString:_selJobName]}];
    
    ccvc.isJobType = YES;
    [ccvc setNaviTitle:@"業種"];
    ccvc.view.backgroundColor = self.view.backgroundColor;
    ccvc.dataList = [self getJogTypeInfoList];
    ccvc.choosedDataBlock = ^(NSDictionary *selInfo) {
      
        _selJobName = [selInfo objectForKey:@"name"];
        _selJobId = [selInfo objectForKey:@"id"];
        
        _workTypeLabel.text = _selJobName;
    };
    [self.navigationController pushViewController:ccvc animated:YES];
}

- (IBAction)capacityBtnClicked:(id)sender {
    
    HOTCommChooseViewController *ccvc = [[HOTCommChooseViewController alloc] initWithNibName:@"HOTCommChooseViewController" bundle:nil choosedInfo:@{@"id":[HOTUtils getString:_selBaoyouzigeId], @"name":[HOTUtils getString:_selBaoyouzigeName]}];
    
    [ccvc setNaviTitle:@"保有資格"];
    ccvc.view.backgroundColor = self.view.backgroundColor;
    ccvc.dataList = [self getCapcityInfoList];
    ccvc.choosedDataBlock = ^(NSDictionary *selInfo) {
        
        _selBaoyouzigeName = [selInfo objectForKey:@"name"];
        _selBaoyouzigeId = [selInfo objectForKey:@"id"];
        
        _capacityLabel.text = _selBaoyouzigeName;
    };
    [self.navigationController pushViewController:ccvc animated:YES];
}

- (IBAction)frendsBtnClicked:(id)sender {
    
    HOTFriendListViewController *flvc = [[HOTFriendListViewController alloc] initWithNibName:@"HOTFriendListViewController" bundle:nil targetUid:self.userInfo.userId];
    [self.navigationController pushViewController:flvc animated:YES];
}

- (IBAction)introductionBtnClicked:(id)sender {
    
    HOTIntroductionSelfViewController *introductionVc = [[HOTIntroductionSelfViewController alloc] initWithNibName:@"HOTIntroductionSelfViewController" bundle:nil];
    //bloodVc.delegate = self;
    introductionVc.orgContent = _introductionLabel.text;
    introductionVc.setIntroductionContentBlock = ^(NSString *content) {
        
        _introductionLabel.text = content;
    };
    [self.navigationController pushViewController:introductionVc animated:YES];
}

- (IBAction)evaluationbtnClicked:(id)sender {
    
    //点击评价按钮
    HOTEvaluationListViewController *elvc = [[HOTEvaluationListViewController alloc] initWithNibName:@"HOTEvaluationListViewController" bundle:nil userId:self.userInfo.userId];
    
    [self.navigationController pushViewController:elvc animated:YES];
    
}

- (IBAction)healthBtnClicked:(id)sender {
    
    HOTCommChooseViewController *ccvc = [[HOTCommChooseViewController alloc] initWithNibName:@"HOTCommChooseViewController" bundle:nil choosedInfo:@{@"id":[HOTUtils getString:_selHealthId], @"name":[HOTUtils getString:_selHealthName]}];
    
    [ccvc setNaviTitle:@"健康診断"];
    ccvc.view.backgroundColor = self.view.backgroundColor;
    ccvc.dataList = [self getHealthInfoList];
    ccvc.choosedDataBlock = ^(NSDictionary *selInfo) {
        
        _selHealthName = [selInfo objectForKey:@"name"];
        _selHealthId = [selInfo objectForKey:@"id"];
        
        _healthLabel.text = _selHealthName;
    };
    [self.navigationController pushViewController:ccvc animated:YES];
}

- (IBAction)previewBtnClicked:(id)sender {
    
    if (![self checkParametersValid]) {

        return;
    }
    
    HOTUserInfo *userInfo = [[HOTUserInfo alloc] init];
    userInfo.userId = self.userInfo.userId;
    userInfo.nick = _nickNameText.text;
    userInfo.sex = _sexPullDownView.selectedModel.value;
    userInfo.birth = _birthdayText.text;
    userInfo.city_id = _cityPullDownView.selectedModel.value;
    userInfo.blood = _selBloodId;
    userInfo.job_id = _selJobId;
    userInfo.job_name = _selJobName;
    userInfo.certification = _selBaoyouzigeId;
    userInfo.health = _selHealthId;
    userInfo.follow_sum = self.userInfo.follow_sum;
    userInfo.rate = self.userInfo.rate;
    userInfo.self_intro = _introductionLabel.text;

    HOTProfileReviewViewController *previewVc = [[HOTProfileReviewViewController alloc] initWithNibName:@"HOTProfileReviewViewController" bundle:nil userInfo:userInfo targetUserId:nil];
    
    [self.navigationController pushViewController:previewVc animated:YES];
}

-(void)comfirmBtnClicked:(id)sender {
    
    if (![self checkParametersValid]) {

        return;
    }
    
    ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:MSG_IS_CONFIRM delegate:self cancelButtonTitle:ALERT_BTN_CANCEL otherButtonTitle:ALERT_BTN_OK];
    popupView.tag = 1001;
    [popupView showInWindow];
}

-(BOOL)checkParametersValid {
    
    NSString *errName = @"";
    HOTInputItemType inputType = 0;
    if ([_nickNameText textIsNullOrEmpty]) {
        
        errName = @"ニックネーム";
        inputType = HOTInputItemText;
    }else if ([_birthdayText textIsNullOrEmpty]) {
        
        errName = @"生年月日";
        inputType = HOTInputItemPullDown;
    }
//    else if ([HOTUtils isNullOrEmpty:_selBloodId]) {
//        
//        errName = @"血液型";
//        inputType = HOTInputItemPullDown;
//    }
//    else if ([HOTUtils isNullOrEmpty:_selJobId]) {
//        
//        errName = @"業種";
//        inputType = HOTInputItemPullDown;
//    }
//    else if (_capacityLabel.text == nil || [_capacityLabel.text isEqualToString:@""]) {
//        
//        errName = @"保有資格";
//        inputType = HOTInputItemPullDown;
//    }
//    else if (_introductionLabel.text == nil || [_introductionLabel.text isEqualToString:@""]) {
//        
//        errName = @"自分紹介";
//        inputType = HOTInputItemText;
//    }
    
    if (errName.length > 0) {
        
        NSString * errMsg = [self getErrMsgWith:errName itemType:inputType];
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:errMsg delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        
        return NO;
    }
    
    
    
    return YES;
}

#pragma mark - 代理
-(void)popupView:(ZZZPopupView *)popupView buttonKind:(ZZZPopupViewBtnKind)btnKind {
    [super popupView:popupView buttonKind:btnKind];
    if (popupView.tag == 1001 && btnKind == ZZZPopupViewConfirmBtnKind) {
        
        [self requestUpdate];
        return;
    }
}

#pragma mark - 私有方法
-(void)hiddenKeyBoard {
    
    [_nickNameText resignFirstResponder];
    [_birthdayText resignFirstResponder];
}

-(NSArray *)getJogTypeInfoList {
    
    if (_jobInfoList == nil) {
        _jobInfoList = [[NSMutableArray alloc] initWithCapacity:31];
    
    
        NSArray *modelList = [HOTUtils getJobPullModelListFromPlist];
        
        for (ZZZPullDownModel *model in modelList) {
            
            NSDictionary *dic = @{@"id":[HOTUtils getString:model.value],
                                  @"name":[HOTUtils getString:model.titleStr]};
            
            [_jobInfoList addObject:dic];
        }
    }
    
    return _jobInfoList;
}

-(NSArray *)getCapcityInfoList {
    
    if (_capcityInfoList == nil) {
        _capcityInfoList = [[NSMutableArray alloc] initWithCapacity:31];
        
        
        NSArray *modelList = [HOTUtils getCapcityPullModelListFromPlist];
        
        for (ZZZPullDownModel *model in modelList) {
            
            NSDictionary *dic = @{@"id":[HOTUtils getString:model.value],
                                  @"name":[HOTUtils getString:model.titleStr]};
            
            [_capcityInfoList addObject:dic];
        }
    }
    
    return _capcityInfoList;
}

-(NSArray *)getHealthInfoList {
    
    if (_healthList == nil) {
        _healthList = [[NSMutableArray alloc] initWithCapacity:31];
        
        
        NSArray *modelList = [HOTUtils getHealthPullModelListFromPlist];
        
        for (ZZZPullDownModel *model in modelList) {
            
            NSDictionary *dic = @{@"id":[HOTUtils getString:model.value],
                                  @"name":[HOTUtils getString:model.titleStr]};
            
            [_healthList addObject:dic];
        }
    }
    
    return _healthList;
}

@end
